package vip.zhenzicheng.algorithm.leetcode.binary_tree;

import vip.zhenzicheng.algorithm.TreeNode;

/**
 * <a href="https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/">二叉树展开为链表 [中等]</a>
 *
 * @author zhenzicheng
 * @date 2022-06-29 14:55
 */
public class FlattenBinaryTreeToLinkedList_114 {

  /*循环实现，空间复杂度O(1)*/
  public void flatten(TreeNode root) {
    while (root != null) {
      if (root.left == null) {
        root = root.right;
      } else {
        // 寻找左子树的最右叶子节点
        TreeNode rightLeaf = root.left;
        while (rightLeaf.right != null) {
          rightLeaf = rightLeaf.right;
        }
        // 将右子树挂到左子树最右叶子节点上
        rightLeaf.right = root.right;
        // 将当前左节点挂到右节点
        root.right = root.left;
        root.left = null; // 置空左侧
      }
    }
  }
}
